<!DOCTYPE html>
<html>
<body>
<script src="../../../resources/js-test.js"></script>

<div id="container"></div>
<pre id="console"></pre>

<script>
description("Tests to ensure ShadowRoot.getElementById works after complex DOM manipulation.");

function createDiv(id)
{
    var div = document.createElement('div');
    div.id = id;
    return div;
}

var A = createDiv('A');
var B = createDiv('B');
var C = createDiv('C');
var D = createDiv('D');
var shadowRootA = A.attachShadow({mode: 'open'});
var shadowRootB = B.attachShadow({mode: 'open'});
var shadowRootC = C.attachShadow({mode: 'open'});

shadowRootA.appendChild(B);
shadowRootB.appendChild(C);
shadowRootC.appendChild(D);

container.appendChild(A);
shouldBe('document.getElementById("A")', 'A');
shouldThrow('shadowRootA.getElementById()');
shouldBe('shadowRootA.getElementById("B")', 'B');
shouldBe('shadowRootB.getElementById("C")', 'C');
shouldBe('shadowRootC.getElementById("D")', 'D');

debug('');
debug('Remove C from shadowRootB');
shadowRootB.removeChild(C);

shouldBe('document.getElementById("A")', 'A');
shouldBe('shadowRootA.getElementById("B")', 'B');
shouldBe('shadowRootB.getElementById("C")', 'null');
shouldBe('shadowRootC.getElementById("D")', 'D');

debug('');
debug('Append C to ShadowRootB, and remove A from document');
shadowRootB.appendChild(C);
container.removeChild(A);

shouldBe('document.getElementById("A")', 'null');
shouldBe('shadowRootA.getElementById("B")', 'B');
shouldBe('shadowRootB.getElementById("C")', 'C');
shouldBe('shadowRootC.getElementById("D")', 'D');

debug('');
debug('Remove C from shadowRootB');
shadowRootB.removeChild(C);

shouldBe('document.getElementById("A")', 'null');
shouldBe('shadowRootA.getElementById("B")', 'B');
shouldBe('shadowRootB.getElementById("C")', 'null');
shouldBe('shadowRootC.getElementById("D")', 'D');

debug('');
debug('Remove D from shadowRootC');
shadowRootC.removeChild(D);

shouldBe('document.getElementById("A")', 'null');
shouldBe('shadowRootA.getElementById("B")', 'B');
shouldBe('shadowRootB.getElementById("C")', 'null');
shouldBe('shadowRootC.getElementById("D")', 'null');

</script>
</body>
</html>
